import { defineStore } from 'pinia';
import type { ItagItem } from '@/types/base';
interface tagsState {
  visitedRoutes: ItagItem[];
}
const BASEPAGE = 'Dashboard'
export const useTagsStore = defineStore('tags', {
  state: (): tagsState => {
    return {
      visitedRoutes: [{
        path: '/dashboard',
        name: 'Dashboard',
        meta: { title: '主页', }
      }]
    };
  },
  actions: {
    addRoute(route: ItagItem) {
      let target = this.visitedRoutes.find((item) => item.path === route.path)
      if (target) {
        if (route.fullPath !== target?.fullPath) Object.assign(target, route)
        return
      }
      this.visitedRoutes.push(route)
    },
    delRoute(route: string) {
      this.visitedRoutes.forEach((item, index) => {
        if (item.path === route) this.visitedRoutes.splice(index, 1)
      })
    },
    delOthersRoutes(route: ItagItem) {
      this.visitedRoutes = this.visitedRoutes.filter((item) => item.name == BASEPAGE || item.path === route.path)
    },
    delLeftRoutes(route: ItagItem) {
      let index = this.visitedRoutes.length
      this.visitedRoutes = this.visitedRoutes.filter((item) => {
        if (item.name === route.name) index = this.visitedRoutes.indexOf(item)
        return item.name == BASEPAGE || index <= this.visitedRoutes.indexOf(item)
      })
    },
    delRightRoutes(route: ItagItem) {
      let index = this.visitedRoutes.length
      this.visitedRoutes = this.visitedRoutes.filter((item) => {
        if (item.name === route.name) index = this.visitedRoutes.indexOf(item)
        return item.name == BASEPAGE || index >= this.visitedRoutes.indexOf(item)
      })
    },
    delAllRoutes() {
      this.visitedRoutes = this.visitedRoutes.filter((item) => item.name == BASEPAGE)
    },
    updateView(route: ItagItem) {
      this.visitedRoutes = this.visitedRoutes.map(e => {
        if (e.path === route.path) {
          e = Object.assign(e, route)
        }
        return e
      })
    }
  }
});